<template>
    <div class="article-con">
        <div class="author-con flex">
            <router-link :to="/user/+article.author._id" class="avatar-box">
                <img :src="article.author.avatar" alt="">
            </router-link>
            <div class="author-info-box flex">
                <router-link :to="/user/+article.author._id" class="nickname ellipsis">
                    <span>{{article.author.nickname}}</span>
                </router-link>
                <div style="color: #909090">
                    <span>{{article.author.createdAt|formatDate2}}</span>
                    <span>阅读 {{article.views}}</span>
                </div>
            </div>
            <button v-if="article.author._id!=loginUser.id" class="follow-button" :class="{followed:isFollow}"
                    @click="onclick_follow">{{isFollow?"已关注":"关注"}}
            </button>
        </div>
        <img :src="article.coverImage" style="width: 100%">

        <h1 class="article-title">{{article.title}}</h1>
        <mavon-editor class="markdown" :toolbarsFlag="false" defaultOpen="preview" :subfield="false"
                      v-model="article.article" :ishljs="true"
                      codeStyle="dark" :boxShadow="false"/>
        <div class="toc"></div>


        <!--    评论-->
        <h4 class="text-center" ref="commentTarget">评论</h4>
        <div class="comment-box flex flex-column" ref="superCommentBox">
            <div class="flex w100">
                <img :src="loginUser.avatar" width="30" height="30" class="circle">
                <el-input v-model="commentText" placeholder="输入评论..." @focus="isShowCommentBtn=true"></el-input>
            </div>
            <button v-show="isShowCommentBtn" class="commentBtn" @click="onclick_comment"
                    :disabled="!commentText.trim().length">评论
            </button>
        </div>
        <div class="comment-block flex align-start" v-for="(comment,i) in commentsList" :key="i">
            <img :src="comment.commitPerson.avatar" width="30" height="30" class="circle">
            <div class="comment-content">
                <div>{{comment.commitPerson.nickname}}</div>
                <p>{{comment.commentText}}</p>
                <div class="reply-con flex jc-between">
                    <span>{{comment.createdAt|formatDate}}</span>
                    <div class="action-box" @click="onclick_reply(i)" ref="actionBox">
                        <i class="iconfont iconhuifu"></i>
                        回复
                    </div>
                </div>
                <ReplyBox class="ReplyBox" @onreply="onreply($event,comment)" ref="ReplyBox"
                          :placeholder="'回复'+comment.commitPerson.nickname+'...'"></ReplyBox>
                <div class="subCommentCon">
                    <SubComment v-for="(item,index) in comment.subComments" :key="index" :comment="item"
                                :superComment="comment._id"></SubComment>
                </div>
            </div>
        </div>

        <!--    左侧固定图标pannel-->
        <div class="article-suspended-panel">
            <div class="iconfont icondianzan panel-btn"
                 :class="{active:userlikeArticles.includes(article._id)}"
                 @click="onclick_likeArticle"
                 :badge="article.like"></div>
            <div class="iconfont iconpinglun panel-btn"
                 @click="onclick_redirectToComment"
                 :badge="article.commentCount"></div>
        </div>
    </div>
</template>

<script>
    import User from "@/components/User.vue";
    import ReplyBox from "@/components/ReplyBox.vue";
    import SubComment from "@/components/SubComment.vue";

    import {mavonEditor} from 'mavon-editor'
    import 'mavon-editor/dist/css/index.css'
    import {TOKEN_KEY} from "@/plugins/http";
    import {genToc} from './utils.js'


    export default {
        components: {
            User,
            ReplyBox,
            SubComment,
            mavonEditor
        },
        mounted() {
            let {id} = this.$route.params;
            this.id = id; // 不在data中定义也可以。data中定义的数据是响应式的。对于获取的ID来说没必要，也算是性能优化
            this.getArticle();
            this.token = localStorage.getItem(TOKEN_KEY);
            this.getArticleComments();
            document.addEventListener("click", this.onClick_el)
        },
        data() {
            return {
                article: {
                    title: "",
                    author: {},
                    like: 0,
                    commentCount: 0
                },
                isFollow: false,
                likeStatus: false,
                commentText: "",
                commentsList: [],
                isShowCommentBtn: false,
                index: null
            };
        },
        computed: {
            userlikeArticles() {
                return this.$store.state.user.likeArticles || [];
            },
            loginUser() {
                return this.$store.state.user
            }
        },
        methods: {
            async getArticle() {
                let res = await this.$http.get("/article/" + this.id);
                this.article = res.data;
                // 生成目录
                this.$nextTick(() => {
                    genToc('.v-show-content', '.toc')
                })
                if (this.token) {
                    this.checkFollowStatus();
                }
                // console.log(this.article);
            },
            async checkFollowStatus() {
                let res = await this.$http.get(
                    "/user/isFollow/" + this.article.author._id
                );
                if (res.code === 0) {
                    this.isFollow = res.data.isFollow;
                }
            },
            async onclick_follow() {
                if (this.isFollow) {
                    let res = await this.$http.delete(
                        "/user/follow/" + this.article.author._id
                    );
                } else {
                    let res = await this.$http.put("/user/follow/" + this.article.author._id);

                }
                this.$store.dispatch("detail");
                this.checkFollowStatus();
            },
            async onclick_likeArticle() {
                let method = this.userlikeArticles.includes(this.id) ? "delete" : "put";
                let res = await this.$http[method]("/user/likeArticle/" + this.id);
                if (res.code == 0) {
                    // 这里是取巧的做法。实际应该管理内部状态用vuex
                    this.getArticle();
                    this.$store.dispatch("detail");
                    this.$message.success(res.message);
                }
            },
            // 评论
            async onclick_comment() {
                let res = await this.$http.post("/comment", {
                    article: this.id,
                    commitPerson: this.loginUser.id,
                    commentText: this.commentText
                });
                if (res.code == 0) {
                    this.commentText = ""
                    this.isShowCommentBtn = false;
                    this.getArticleComments();
                    this.article.commentCount++
                    this.$message.success("评论成功")
                }
            },
            // 获取文章评论
            async getArticleComments() {
                let res = await this.$http.get("/comments", {params: {article: this.id}});
                if (res.code == 0) {
                    this.commentsList = res.data;
                    // console.log(this.commentsList)
                }
            },
            async onreply(text, comment) {
                console.log(text);
                console.log(comment)
                let res = await this.$http.post("/reply", {
                    superComment: comment._id,
                    replyedPerson: comment.commitPerson._id,
                    article: this.id,
                    commitPerson: this.loginUser.id,
                    commentText: text,
                })
                console.log(res)
                if (res.code == 0) {
                    this.getArticleComments();
                    this.$refs.ReplyBox[this.index].$el.style.display = "none";
                    this.$refs.ReplyBox[this.index].commentText = "";
                    this.article.commentCount++
                    this.$message.success("回复成功")
                }

            },
            onClick_el(e) {
                // console.log(this.$refs.actionBox)
                // console.log(this.$refs.actionBox[this.index])
                // console.log(this.$refs.ReplyBox)
                // console.log(this.$refs.ReplyBox[this.index])
                if (this.index != null && this.$refs.actionBox[this.index] && !this.$refs.actionBox[this.index].contains(e.target) && this.$refs.ReplyBox[this.index] && !this.$refs.ReplyBox[this.index].$el.contains(e.target)) {
                    this.$refs.ReplyBox[this.index].$el.style.display = "none"
                    this.$refs.ReplyBox[this.index].commentText = ""
                }
                if (this.$refs.superCommentBox && !this.$refs.superCommentBox.contains(e.target)) {
                    this.isShowCommentBtn = false
                }
            },
            onclick_reply(i) {
                if (this.index != null) {
                    this.$refs.ReplyBox[this.index].$el.style.display = "none"
                }
                this.index = i;
                this.$refs.ReplyBox[i].$el.style.display = "flex";
            },

            // 点击左侧评论图标按钮页面滚动至评论列表处
            onclick_redirectToComment() {
                // console.log(this.$refs.commentTarget.offsetTop)
                // this.$refs.commentTarget.scrollIntoView() /*可行*/
                // widow 根据浏览器滚动条，如果你是要在某个盒子里面产生滑动，记得修改
                window.scrollTo({
                    'top': this.$refs.commentTarget.offsetTop,
                    'behavior': 'smooth'
                })
            }
        },
        beforeDestroy() {
            window.removeEventListener("click", this.onClick_el)
        }
    };
</script>

<style scoped lang="less">
    .article-con {
        padding: 24px;
        position: relative;

        .author-con {
            margin-bottom: 24px;

            .avatar-box {
                display: block;
                width: 40px;
                height: 40px;
                margin-right: 12px;

                img {
                    width: 100%;
                    height: 100%;
                    border-radius: 50%;
                }
            }

            .author-info-box {
                flex-grow: 1;
                flex-direction: column;
                align-items: flex-start;

                .nickname {
                    display: inline-block;
                    max-width: 100%;
                    font-size: 1.3rem;
                    font-weight: 700;
                    color: #333;
                }
            }

            .follow-button {
                margin: 0 0 0 auto;
                padding: 0;
                width: 55px;
                height: 26px;
                font-size: 13px;
                border: 1px solid #6cbd45;
                color: #6cbd45;
                background-color: #fff;
            }

            .followed {
                color: #fff;
                border-color: #6cbd45;
                background-color: #6cbd45;
            }
        }

        .article-title {
            margin: 20px 0;
            font-size: 2.5*12px;
            font-weight: 700;
            line-height: 1.5;
        }
    }

    .article-suspended-panel {
        position: fixed;
        margin-left: -7rem;
        top: 16rem;

        .panel-btn {
            position: relative;
            margin-bottom: .75rem;
            width: 3rem;
            height: 3rem;
            color: #B5BAC6;
            background-color: #fff;
            background-position: 50%;
            background-repeat: no-repeat;
            border-radius: 50%;
            box-shadow: 0 2px 4px 0 rgba(0, 0, 0, .04);
            cursor: pointer;

            &:before {
                position: absolute;
                top: 50%;
                left: 50%;
                font-size: 18px;
                transform: translate(-50%, -50%);
            }

            &:after {
                content: attr(badge);
                position: absolute;
                top: 0;
                left: 75%;
                padding: .1rem .4rem;
                font-size: 1rem;
                text-align: center;
                line-height: 1;
                white-space: nowrap;
                color: #fff;
                background-color: #b2bac2;
                border-radius: .7rem;
                transform-origin: left top;
                transform: scale(.75);
            }
        }

        .active {
            color: #6cbd45;

            &:after {
                background-color: #74ca46;
            }
        }
    }

    .comment-box {
        background-color: #fafbfc;
        margin: 16px 0;
        padding: 12px 16px;
        border-radius: 3px;

        img {
            margin-right: 12px;
        }

        .el-input {
            flex-grow: 1;
        }
    }

    .commentBtn {
        flex: 0 0 auto;
        margin-left: auto;
        margin-top: 8px;
        padding: .5rem 1.3rem;
        font-size: 1rem;
        color: #fff;
        background-color: #027fff;
        border-radius: 2px;

        &:disabled {
            cursor: default;
            opacity: .4;
        }
    }

    .reply-con {
        margin: 12px 0;
        padding-right: 12px;
    }

    .comment-block {
        margin-bottom: 10px;
    }

    .comment-content {
        margin-left: 10px;
        flex-grow: 1;
        border-bottom: 1px solid #f1f1f1
    }

    .ReplyBox {
        display: none;
    }

    .subCommentCon {
        width: 100%;
        background-color: #fafbfc;
        margin: 12px 0;
    }

    .toc {
        position: fixed;
        right: 3rem;
        top: 15rem;
        width: 200px;
        color: #2185d0;
        background: #fff;
        padding: 10px;
        z-index: 1501;
    }

</style>
